/* COPYRIGHT_CHUNFENG */
#include "cf_std.h"
#include "cf_network.h"
#define USE_MESSAGE_LOG
#define USE_ERROR_LOG
#include "lcf_log.h"


int ifconfig(unsigned int ioc_req, void * req)
{
	int sockfd;
	int res;
	struct ifreq;
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sockfd == -1){
		LCF_ERR("init socket fd failed:");
		perror(NULL);
		return -1;
	}
	res = ioctl(sockfd, ioc_req, req);
	close(sockfd);
	return res;
}

int get_if_flags(const char* eth, short* flags)
{
	struct ifreq ifreq0;
	memset(&ifreq0, 0, sizeof(struct ifreq));
	strncpy(ifreq0.ifr_name, eth, IFNAMSIZ);
	if( -1 == ifconfig(SIOCGIFFLAGS, &ifreq0)){
		LCF_ERR("ioctl failed:");
		perror(NULL);
		return -1;
	}
	*flags = ifreq0.ifr_flags;
    return 0;
}

int ifconfig_is_link_ok(const char* ifname)
{
    short flags;
    if(get_if_flags(ifname, &flags) == -1)
        return -1;
	if(flags & IFF_RUNNING)
        return 1;
    else
        return 0;
}

int is_link_ok_auto(const char* ifname)
{
    static int(*cached_is_link_ok_func)(const char*) = NULL;
    int res;
    if(cached_is_link_ok_func){
        res = cached_is_link_ok_func(ifname);
        if(res != -1)
            return res;
    }
    if(-1 != (res = ifconfig_is_link_ok(ifname))){
        cached_is_link_ok_func = ifconfig_is_link_ok;
        return res;
    }
    return -1;
}

int ifconfig_get_addr(const char* ifname, struct sockaddr* addr)
{
    struct ifconf ifc;
    int alloced_size, i;
    
    memset(&ifc, 0, sizeof(struct ifconf));
    alloced_size = 10*sizeof(struct ifreq);
    while(1){
        ifc.ifc_len = alloced_size;
        ifc.ifc_buf = malloc(ifc.ifc_len);
        if(ifconfig(SIOCGIFCONF, &ifc) < 0){
            free(ifc.ifc_buf);
            return -1;
        }
        if(ifc.ifc_len == alloced_size){
            free(ifc.ifc_buf);
            alloced_size += 10*sizeof(struct ifreq);
            continue;
        }else
            break;
    }
    for(i=0; i < ifc.ifc_len/sizeof(struct ifreq); i++){
        LCF_DBG("ifname%d:%s\n", i, ifc.ifc_req[i].ifr_name);
        if(!strncmp(ifc.ifc_req[i].ifr_name, ifname, IFNAMSIZ)){
            memcpy(addr, &ifc.ifc_req[i].ifr_addr, sizeof(struct sockaddr));
            free(ifc.ifc_buf);
            return 0;
        }
    }
    free(ifc.ifc_buf);
    return -1;
}

int get_if_mask(const char* ifname, struct sockaddr* addr)
{
    return 0;
}

int get_if_broadcast_addr(const char* ifname, struct sockaddr* addr)
{
    return 0;
}

int get_host_by_name_safe()
{
    return 0;
}

#if 0
int main(int argc, char** argv)
{
	short flags;
	flags = get_if_flags(argv[1]);
    ifconfig_get_addr(NULL, NULL);
	if(flags == -1)
		return -1;
	if(flags & IFF_UP)
		printf("IFF_UP\n");
	if(flags & IFF_RUNNING)
		printf("IFF_RUNNING\n");
	return 0;
}
#endif
